﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NHibernate;
using NHibernate.Criterion;

using Revis.VClinicNet.Core.Domain.Repository;

namespace Revis.VClinicNet.Core.Domain.Persistence.Nh
{
    public class RepositoryBase<T> : IRepository<T> where T : class
    {
        protected ISessionFactory SessionFactory { get; private set; }

        protected ISession Session
        {
            get { return SessionFactory.GetCurrentSession(); }
        }

        protected void InSession(Action<ISession> action)
        {
            action(Session);
        }

        public RepositoryBase(ISessionFactory factory)
        {
            SessionFactory = factory;
        }

        public virtual void Store(T obj)
        {
            Session.SaveOrUpdate(obj);
        }

        public virtual T Find(long id)
        {
            return Session.Get<T>(id);
        }

        public virtual IList<T> FindAll()
        {
            IList<T> finded = Session.CreateCriteria<T>().List<T>();
            return finded;
        }

        public virtual IList<T> FindBy(string field, string value)
        {
            IList<T> finded = null;
            try {
                finded = Session.CreateCriteria<T>("t")
                    .Add(Expression.Like(field, value, MatchMode.Anywhere)).List<T>();
            } catch (QueryException) {
                finded = null;
            }
            return finded;
        }

        public virtual void Delete(T obj)
        {
            Session.Delete(obj);
        }
    }
}
